package main

import (
	proto "com/hr/go-muke/grpc/protobuf/stream"
	"fmt"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"io"
	"net"
	"strconv"
	"sync"
	"time"
)

/**
 * @Description
 * @Author huran
 * @Date
 * @Param
 * @return
 **/
type server struct {
	proto.GreeterServer
}

// GetStream 服务端流模式
func (s *server) GetStream(req *proto.StreamReq, res proto.Greeter_GetStreamServer) error {
	i := 0
	for {
		i++
		res.Send(&proto.StreamRsp{Data: strconv.FormatInt(time.Now().UnixMilli(), 10)})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	//return errors.New("结束")
	return nil
}

// PutStream 客户端流模式
func (s *server) PutStream(c proto.Greeter_PutStreamServer) error {
	for {
		fmt.Println("%p", c)
		if recv, err := c.Recv(); err != nil {
			fmt.Println("=========>>>", err)

		} else {
			fmt.Println(recv)
			fmt.Println("err 111")
			return errors.New("111")
		}
	}
	return nil
}

// AllStream 双向流
func (s *server) AllStream(all proto.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			recv, err := all.Recv()
			if err == io.EOF {
				fmt.Println("server recv EOF")
				return
			}
			if err != nil {
				fmt.Println("server recv:", err)
				return
			}
			fmt.Println("收到客户端消息:", recv.Data)
		}
	}()
	go func() {
		defer wg.Done()
		for {
			req := proto.StreamReq{Data: "你好，我是服务器"}

			err := all.SendMsg(&req)
			if err == io.EOF {
				fmt.Println("server send EOF")
				return
			}
			if err != nil {
				fmt.Println("server send:", err)
				return
			}
			fmt.Println("server send msg :", req)
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	fmt.Println("server  done")
	return nil
}
func main() {
	listen, err := net.Listen("tcp", ":9999")
	if err != nil {
		panic(err)
	}
	newServer := grpc.NewServer()
	proto.RegisterGreeterServer(newServer, &server{})
	err = newServer.Serve(listen)
	if err != nil {
		panic(err)
	}
}
